from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from django.utils.html import format_html
from bs4 import BeautifulSoup

import jieba.analyse
from . import models
from ..account.models import Account

admin.AdminSite.site_title = '博客管理'
admin.AdminSite.site_header = '博客管理'


# from import_export import resources
#
# class CategoryResource(resources.ModelResource):
#
#     class Meta:
#         model = models.Category
#         skip_unchanged = True   # 导入数据时，如果该条数据未修改过，则会忽略（默认根据id去匹配数据，可通过定义import_id_fields去更改）
#         exclude = ('date', 'attachment')   # 导出数据时，将不会导出exclude里的字段。必须定义fields或exclude中的一项。fields表示导出哪些字段
#         export_order = ('device_name', 'id', 'area_company', 'site', 'device_id', 'device_type', 'account', 'password',)    # 定义导出时字段的顺序

class BaseAdmin:
    # resource_class = CategoryResource
    list_max_show_all = 100
    list_per_page = 20
    # # 增加自定义按钮
    # actions = ['custom_button']
    # def custom_button(self, request, queryset):
    #     pass
    # # 显示的文本，与django admin一致
    # custom_button.short_description = '测试按钮'
    # # icon，参考element-ui icon与https://fontawesome.com
    # custom_button.icon = 'fas fa-audio-description'
    # # 指定element-ui的按钮类型，参考https://element.eleme.cn/#/zh-CN/component/button
    # custom_button.type = 'danger'
    # # 给按钮追加自定义的颜色
    # custom_button.style = 'color:black;'

    # list_display = ('__str__',)
    # list_display_links = ()
    # list_filter = ()
    # list_select_related = False
    # list_per_page = 100
    # list_max_show_all = 200
    # list_editable = ()
    # search_fields = ()
    # date_hierarchy = None
    # save_as = False
    # save_as_continue = True
    save_on_top = True
    # paginator = Paginator
    # preserve_filters = True
    # inlines = []
    #
    # # Custom templates (designed to be over-ridden in subclasses)
    # add_form_template = None
    # change_form_template = None
    # change_list_template = None
    # delete_confirmation_template = None
    # delete_selected_confirmation_template = None
    # object_history_template = None
    # popup_response_template = None
    #
    # # Actions
    # actions = []
    # action_form = helpers.ActionForm
    # actions_on_top = True
    # actions_on_bottom = False
    # actions_selection_counter = True
    # checks_class = ModelAdminChecks


@admin.register(models.Category)
class CategoryAdmin(BaseAdmin, ImportExportModelAdmin):
    list_display = ['nid', 'name', 'get_article_num']
    search_fields = ['name']

    def get_article_num(self, obj):
        return obj.articles.count()

    get_article_num.short_description = '文章数'


@admin.register(models.Article)
class ArticleAdmin(BaseAdmin, ImportExportModelAdmin):
    list_display = ['nid', 'get_thumbnail_img', 'title', 'get_category_name', 'top',
                    'comment_count', 'up_count', 'update_time']

    list_filter = ['category', 'top']
    search_fields = ['title', 'category']

    def get_thumbnail_img(self, obj):
        return format_html(
            f'<img src="{obj.thumbnail}" width="100" height="100" style="border: 2px solid #c7c0c0;">') if obj.thumbnail else ""

    def get_category_name(self, obj):
        return obj.category.name

    get_thumbnail_img.short_description = "封面"
    get_category_name.short_description = "分类"

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'author':
            # 添加文章是限制外键作者下拉框数据
            kwargs["queryset"] = Account.objects.filter(is_superuser=True)
        return super(ArticleAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    def save_model(self, request, obj, form, change):
        """保存文章"""
        soup = BeautifulSoup(obj.content, 'html.parser')
        obj.desc = soup.text[0:150]
        # tf-idf
        keywords = jieba.analyse.extract_tags(soup.text)
        obj.keywords = ','.join(keywords)
        obj.save()


@admin.register(models.Diary)
class DiaryAdmin(BaseAdmin, ImportExportModelAdmin):
    list_display = ['get_content', 'create_time']

    def get_content(self, obj):
        return format_html(obj.content)

    get_content.short_description = "内容"


@admin.register(models.Comment)
class CommentAdmin(BaseAdmin, ImportExportModelAdmin):
    list_display = ['nid', 'get_article', 'get_user', 'get_parent', 'get_content', 'create_time']
    list_filter = ['article', 'user']
    search_fields = ['user', 'content']

    def get_content(self, obj):
        return format_html(obj.content)

    def get_user(self, obj):
        return obj.user.username

    def get_article(self, obj):
        return obj.article.nid

    def get_parent(self, obj):
        if obj.parent:
            return f'回复({obj.parent.nid})'
        return f'评论({obj.article.nid})'

    get_content.short_description = "内容"
    get_user.short_description = '评论者'
    get_article.short_description = '文章'
    get_parent.short_description = '父级'


@admin.register(models.Message)
class MessageAdmin(BaseAdmin, ImportExportModelAdmin):
    list_display = ['nid', 'get_user', 'get_parent', 'get_content', 'create_time']
    list_filter = ['user']
    search_fields = ['user', 'content']

    def get_content(self, obj):
        return format_html(obj.content)

    def get_user(self, obj):
        return obj.user.username

    def get_parent(self, obj):
        if obj.parent:
            return f'站长回复'
        return f'留言'

    get_content.short_description = "内容"
    get_user.short_description = '留言者'
    get_parent.short_description = '父级'


@admin.register(models.Friend)
class FriendAdmin(BaseAdmin, ImportExportModelAdmin):
    list_display = ['site_name', 'get_site_link', 'get_site_icon', 'site_desc']
    search_fields = ['site_name', 'get_site_link', 'site_desc']

    def get_site_link(self, obj):
        return format_html(f'<a target="_blank" href="{obj.site_link}">{obj.site_link}</a>')

    get_site_link.short_description = '网址'

    def get_site_icon(self, obj):
        return format_html(f'<a target="_blank" href="{obj.site_icon}">{obj.site_icon}</a>')

    get_site_icon.short_description = '图标'
